﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Finisar.SQLite;
using CustomerEmailer.Common;
using System.Runtime.InteropServices;
using System.Collections;
using System.Xml.Linq;
using System.Xml;
using System.Threading;
using System.IO;
using System.Net;

namespace CustomerEmailer
{
    public partial class History : Form
    {
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd,
                         int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();
        SQLiteConnection sql_con;
        private bool finishedSearchFlag = true;

        public History()
        {
            InitializeComponent();
        }

        private void History_Load(object sender, EventArgs e)
        {
            Utils.historyRevision = 0;
            SyncTimer_Tick(null, null);
            //setup();
        }

        private void setup()
        {
            sql_con = new SQLiteConnection("Data Source=History.db;Version=3;New=False;Compress=True;");
            SQLiteCommand sql_cmd;
            SQLiteDataAdapter DB;
            DataSet DS = new DataSet();
            DataTable DT = new DataTable();
            string CommandText;
            sql_cmd = sql_con.CreateCommand();
            CommandText = "select contacts_mails.email,mails.date,mails.headline,mails.desc,contacts_mails.contactname,mails.sentFrom from mails,contacts_mails where contacts_mails.maildate=mails.date ORDER BY mails.date DESC";
            DB = new SQLiteDataAdapter(CommandText, sql_con);
            DS.Reset();
            DB.Fill(DS);
            DT = DS.Tables[0];
            dgvHistory.DataSource = DT;
            string sentTo = "";
            string mailID = "";
            if (dgvHistory.Rows.Count > 0)
                mailID = (string)dgvHistory["date", 0].Value;
            for (int i = 0, j = 0; i < DT.Rows.Count; i++, j++)
            {
                if (mailID == (string)dgvHistory["date", j].Value)
                {
                    sentTo += "," + (string)dgvHistory["contactname", j].Value + "[" + (string)dgvHistory["email", j].Value + "]";
                    if (i != 0)
                    {
                        dgvHistory.Rows.RemoveAt(j);
                        j--;
                    }
                }
                else
                {
                    dgvHistory["contactname", j - 1].Value = sentTo;
                    sentTo = (string)dgvHistory["contactname", j].Value + "[" + (string)dgvHistory["email", j].Value + "]";
                    long ticks;
                    long.TryParse((string)dgvHistory["date", j - 1].Value, out ticks);
                    dgvHistory["email", j - 1].Value = (new DateTime(ticks)).ToString();
                    mailID = (string)dgvHistory["date", j].Value;
                }
            }
            if (dgvHistory.Rows.Count > 0)
            {
                dgvHistory["contactname", dgvHistory.Rows.Count - 1].Value = sentTo;
                long ticks;
                long.TryParse((string)dgvHistory["date", dgvHistory.Rows.Count - 1].Value, out ticks);
                dgvHistory["email", dgvHistory.Rows.Count - 1].Value = (new DateTime(ticks)).ToString();
            }
            dgvHistory.Columns["desc"].Visible = false;
            dgvHistory.Columns["contactname"].Visible = false;
            dgvHistory.Columns["date"].Visible = false;
        }

        private void tbMailSearch_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void dgvHistory_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void History_Paint(object sender, PaintEventArgs e)
        {
            this.Region = new System.Drawing.Region(Utils.drawRoundedRect(0, 0, 15, this.Height, this.Width));
            Utils.drawBorder(0, 0, 15, this.Height, this.Width, e);
        }

        private void btnComplete_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnComplete_MouseDown(object sender, MouseEventArgs e)
        {
            
        }

        private void History_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        private void dgvHistory_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            lvSent.Clear();
            htmlEditorControl.BodyHtml = (string)dgvHistory["desc", e.RowIndex].Value;
            SQLiteCommand sql_cmd;
            SQLiteDataAdapter DB;
            DataSet DS = new DataSet();
            DataTable DT = new DataTable();
            string CommandText;
            sql_cmd = sql_con.CreateCommand();
            CommandText = "select contactname,email from contacts_mails where maildate=" + (string)dgvHistory["date", e.RowIndex].Value;
            DB = new SQLiteDataAdapter(CommandText, sql_con);
            DS.Reset();
            DB.Fill(DS);
            DT = DS.Tables[0];
            for (int i = 0; i < DT.Rows.Count; i++)
            {
                lvSent.Items.Add(DT.Rows[i]["contactname"] + "[" + DT.Rows[i]["email"] + "]");
            }
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("IExplore", " http://www.socialbiz.co.il");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SQLiteCommand sql_cmd;
            SQLiteDataAdapter DB;
            DataSet DS = new DataSet();
            DataTable DT = new DataTable();
            string CommandText;
            sql_cmd = sql_con.CreateCommand();
            CommandText = "select contacts_mails.email,mails.date,mails.headline,mails.desc,contacts_mails.contactname,mails.sentFrom from mails,contacts_mails where contacts_mails.maildate=mails.date AND (lower(email) like '%" + tbMailSearch.Text.ToLower() + "%' OR lower(contactname) like '%" + tbMailSearch.Text.ToLower() + "%') ORDER BY mails.date DESC";
            DB = new SQLiteDataAdapter(CommandText, sql_con);
            DS.Reset();
            DB.Fill(DS);
            DT = DS.Tables[0];
            dgvHistory.DataSource = DT;
            string sentTo = "";
            string mailID = "";
            if (dgvHistory.Rows.Count > 0)
                mailID = (string)dgvHistory["date", 0].Value;
            for (int i = 0, j = 0; i < DT.Rows.Count; i++, j++)
            {
                if (mailID == (string)dgvHistory["date", j].Value)
                {
                    sentTo += "," + (string)dgvHistory["contactname", j].Value + "[" + (string)dgvHistory["email", j].Value + "]";
                    if (i != 0)
                    {
                        dgvHistory.Rows.RemoveAt(j);
                        j--;
                    }
                }
                else
                {
                    dgvHistory["contactname", j - 1].Value = sentTo;
                    sentTo = (string)dgvHistory["contactname", j].Value + "[" + (string)dgvHistory["email", j].Value + "]";
                    long ticks;
                    long.TryParse((string)dgvHistory["date", j - 1].Value, out ticks);
                    dgvHistory["email", j - 1].Value = (new DateTime(ticks)).ToString();
                    mailID = (string)dgvHistory["date", j].Value;
                }
            }
            if (dgvHistory.Rows.Count > 0)
            {
                dgvHistory["contactname", dgvHistory.Rows.Count - 1].Value = sentTo;
                long ticks;
                long.TryParse((string)dgvHistory["date", dgvHistory.Rows.Count - 1].Value, out ticks);
                dgvHistory["email", dgvHistory.Rows.Count - 1].Value = (new DateTime(ticks)).ToString();
            }
            else
            {
                MessageBox.Show("לא נמצאו תוצאות מתאימות");
            }
        }

        private void SyncTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                long toRevision = 0;
                if (shouldSync(ref toRevision))
                {
                    lbSync.Text = "מסתנכרן...";
                    syncServer();
                    setup();
                    Utils.historyRevision = toRevision;
                    lbSync.Text = "סונכרן לאחרונה ב " + DateTime.Now.ToString();
                }
            }
            catch (Exception ex)
            {
                lbSync.Text = "לא ניתן להתחבר לשרת. אנא שנה הגדרות שרת.";
                SyncTimer.Enabled = false;
                SyncTimer.Stop();
            }
        }

        public static bool shouldSync(ref long toRevision)
        {
            //string myhash=Utils.getXMLHash(XML_FILE_LOCATION);
            //Initialization, we use localhost, change if applicable
            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?shouldSyncHistory");
            //This time, our method is GET.
            WebReq.Timeout = 1000;
            WebReq.Method = "GET";
            //From here on, it's all the same as above.
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

            Stream Answer = WebResp.GetResponseStream();
   
            StreamReader _Answer = new StreamReader(Answer);
            toRevision = long.Parse(_Answer.ReadToEnd());
            Answer.Close();
            return (toRevision != Utils.historyRevision);
        }

        public static void syncServer()
        {
            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?syncHistory");
            WebReq.Method = "GET";
          //  WebReq.Timeout = 5000;
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
            Stream Answer = WebResp.GetResponseStream();
            FileStream historyFile = new FileStream(Utils.GetMainFolderLocation("History.db"), FileMode.Create, FileAccess.Write, FileShare.None);
            byte[] buffServer = new byte[1024];
            try
            {
                int readbytes = 1;
                while (readbytes > 0)
                {
                    readbytes = Answer.Read(buffServer, 0, buffServer.Length);
                    historyFile.Write(buffServer, 0, readbytes);
                }
                historyFile.Close();
                Answer.Close();
            }
            catch (System.UnauthorizedAccessException notAdminException)
            {
                MessageBox.Show("אנא הרץ את האפליקציה כמנהל");
            }
            catch (IOException exception)
            {
                //TODO: write better alert
                MessageBox.Show("הקובץ כרגע בשימוש");
            }
        }

    }
}
